<template>
  <div class="cart-container">
    <a-card class="cart-card">
      <!-- 空购物车状态 -->
      <a-empty
        v-if="storeGroups.length === 0"
        description="购物车是空的"
        :image="Empty.PRESENTED_IMAGE_SIMPLE"
      />

      <!-- 按店铺分组显示购物车商品 -->
      <template v-else>
        <div
          v-for="store in storeGroups"
          :key="store.storeId"
          class="store-group"
        >
          <!-- 店铺信息头部 -->
          <div class="store-header">
            <div class="store-info">
              <a-checkbox
                :checked="
                  store.cartItems.length > 0 &&
                  store.cartItems.every((item) => item.selected === 1)
                "
                @change="() => handleStoreSelectAll(store)"
              >
                {{ store.storeName }}
              </a-checkbox>
            </div>
          </div>

          <!-- 商品列表头部 -->
          <div class="cart-header">
            <div class="select-all"></div>
            <div class="header-item">商品信息</div>
            <div class="header-item">单价</div>
            <div class="header-item">数量</div>
            <div class="header-item">小计</div>
            <div class="header-item">操作</div>
          </div>

          <!-- 店铺商品列表 -->
          <div class="cart-items">
            <div
              v-for="item in store.cartItems"
              :key="item.id"
              class="cart-item"
            >
              <div class="item-select">
                <a-checkbox
                  :checked="item.selected === 1"
                  @change="() => handleSelectItem(item)"
                />
              </div>
              <div class="item-info">
                <img
                  :src="getImageUrl(item.productImage)"
                  :alt="item.productName"
                  class="item-image"
                  @error="handleImageError"
                />
                <div class="item-details">
                  <div class="item-name">{{ item.productName }}</div>
                  <div class="item-size">尺码：{{ item.size }}</div>
                </div>
              </div>
              <div class="item-price">
                ¥{{ item.price?.toFixed(2) ?? "0.00" }}
              </div>
              <div class="item-quantity">
                <a-input-number
                  v-model:value="item.quantity"
                  :min="1"
                  :max="99"
                  @change="(value: number) => handleQuantityChange(item, value)"
                />
              </div>
              <div class="item-total">
                ¥{{ ((item.price ?? 0) * (item.quantity ?? 0)).toFixed(2) }}
              </div>
              <div class="item-actions">
                <a-button type="link" @click="handleRemoveItem(item)" danger>
                  删除
                </a-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 购物车底部 -->
        <div class="cart-footer">
          <div class="footer-left">
            <a-checkbox
              :checked="
                storeGroups.length > 0 &&
                storeGroups.every((store) =>
                  store.cartItems.every((item) => item.selected === 1)
                )
              "
              @change="handleSelectAll"
            >
              全选
            </a-checkbox>
            <a-button type="link" @click="handleBatchDelete" danger>
              删除选中商品
            </a-button>
          </div>
          <div class="footer-right">
            <div class="total-info">
              <span>已选择 {{ selectedCount }} 件商品</span>
              <span v-if="!canCheckout" class="warning-text">
                (只能选择同一店铺的商品结算)
              </span>
              <span class="total-price">
                总计：<span class="price">¥{{ totalPrice.toFixed(2) }}</span>
              </span>
            </div>
            <a-button
              type="primary"
              size="large"
              :disabled="!canCheckout"
              @click="handleCheckout"
            >
              结算
            </a-button>
          </div>
        </div>
      </template>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { Empty, message } from "ant-design-vue";
import { useRouter } from "vue-router";
import {
  getCartItemsByStoreUsingGet,
  removeFromCartUsingPost,
  updateQuantityUsingPost,
  updateSelectedUsingPost,
} from "@/api/shoppingCartController";
import API from "@/api";

interface StoreCartGroup {
  storeId: string;
  storeName: string;
  cartItems: API.ShoppingCartItemVO[];
  allSelected: boolean;
}

const router = useRouter();

// 按店铺分组的购物车数据
const storeGroups = ref<StoreCartGroup[]>([]);

// 加载购物车数据
const loadCartItems = async () => {
  try {
    const res = await getCartItemsByStoreUsingGet();
    if (res.data?.data) {
      const validStores = res.data.data.filter(
        (store): store is Required<API.StoreCartGroupVO> =>
          Boolean(store?.storeId) &&
          typeof store?.storeName === "string" &&
          Array.isArray(store?.cartItems)
      );

      storeGroups.value = validStores.map((store) => ({
        storeId: store.storeId.toString(),
        storeName: store.storeName,
        cartItems: store.cartItems || [],
        allSelected: (store.cartItems || []).every(
          (item) => item.selected === 1
        ),
      }));
    }
  } catch (error) {
    message.error("获取购物车数据失败");
  }
};

// 计算每个店铺的全选状态
const updateStoreAllSelected = () => {
  storeGroups.value.forEach((store: StoreCartGroup) => {
    store.allSelected =
      store.cartItems.length > 0 &&
      store.cartItems.every((item) => item.selected === 1);
  });
};

// 全选状态
const allSelected = computed({
  get: () =>
    storeGroups.value.length > 0 &&
    storeGroups.value.every((store: StoreCartGroup) =>
      store.cartItems.every((item) => item.selected === 1)
    ),
  set: (value: boolean) => {
    storeGroups.value.forEach((store: StoreCartGroup) => {
      store.cartItems.forEach((item) => (item.selected = value ? 1 : 0));
    });
  },
});

// 选中商品数量
const selectedCount = computed(() =>
  storeGroups.value.reduce(
    (total: number, store: StoreCartGroup) =>
      total + store.cartItems.filter((item) => item.selected === 1).length,
    0
  )
);

// 总价
const totalPrice = computed(() =>
  storeGroups.value.reduce(
    (total, store) =>
      total +
      store.cartItems
        .filter((item) => item.selected === 1)
        .reduce(
          (sum, item) => sum + (item.price ?? 0) * (item.quantity ?? 0),
          0
        ),
    0
  )
);

// 检查是否可以结算（只能选择同一店铺的商品）
const canCheckout = computed(() => {
  const selectedStores = new Set(
    storeGroups.value
      .flatMap((store) => store.cartItems)
      .filter((item) => item.selected === 1)
      .map((item) => item.storeId?.toString())
  );
  return selectedStores.size === 1 && selectedCount.value > 0;
});

// 处理店铺全选
const handleStoreSelectAll = async (store: StoreCartGroup) => {
  try {
    // 获取当前店铺商品的选中状态
    const currentSelected = store.cartItems.every(
      (item) => item.selected === 1
    );
    // 如果当前是全选，则取消全选；如果当前不是全选，则全选
    const newSelected = !currentSelected;

    const promises = store.cartItems.map((item) =>
      updateSelectedUsingPost({
        id: item.id,
        selected: newSelected ? 1 : 0,
      })
    );
    await Promise.all(promises);
    await loadCartItems();
  } catch (error) {
    message.error("更新选中状态失败");
  }
};

// 处理全选
const handleSelectAll = async () => {
  try {
    // 获取当前所有商品的选中状态
    const currentSelected = storeGroups.value.every((store) =>
      store.cartItems.every((item) => item.selected === 1)
    );
    // 如果当前是全选，则取消全选；如果当前不是全选，则全选
    const newSelected = !currentSelected;

    const allItems = storeGroups.value.flatMap((store) => store.cartItems);
    const promises = allItems.map((item) =>
      updateSelectedUsingPost({
        id: item.id,
        selected: newSelected ? 1 : 0,
      })
    );
    await Promise.all(promises);
    await loadCartItems();
  } catch (error) {
    message.error("更新选中状态失败");
  }
};

// 处理单个商品选中
const handleSelectItem = async (item: API.ShoppingCartItemVO) => {
  try {
    await updateSelectedUsingPost({
      id: item.id,
      selected: item.selected === 1 ? 0 : 1,
    });
    await loadCartItems();
  } catch (error) {
    message.error("更新选中状态失败");
  }
};

// 处理数量变化
const handleQuantityChange = async (
  item: API.ShoppingCartItemVO,
  value: number
) => {
  try {
    await updateQuantityUsingPost({
      id: item.id,
      quantity: value,
    });
    await loadCartItems();
  } catch (error) {
    message.error("更新数量失败");
  }
};

// 处理删除商品
const handleRemoveItem = async (item: API.ShoppingCartItemVO) => {
  try {
    await removeFromCartUsingPost({
      id: item.id,
    });
    await loadCartItems();
    message.success("删除成功");
  } catch (error) {
    message.error("删除失败");
  }
};

// 批量删除选中商品
const handleBatchDelete = async () => {
  try {
    const selectedItems = storeGroups.value
      .flatMap((store) => store.cartItems)
      .filter((item) => item.selected === 1);

    for (const item of selectedItems) {
      await removeFromCartUsingPost({
        id: item.id,
      });
    }
    await loadCartItems();
    message.success("删除成功");
  } catch (error) {
    message.error("删除失败");
  }
};

// 结算
const handleCheckout = () => {
  if (!canCheckout.value) {
    message.warning("只能选择同一店铺的商品进行结算");
    return;
  }

  const selectedItems = storeGroups.value
    .flatMap((store) => store.cartItems)
    .filter((item) => item.selected === 1);

  router.push({
    path: "/order/create",
    query: {
      from: "cart",
      items: selectedItems.map((item) => item.id).join(","),
    },
  });
};

// 添加图片处理函数
const getImageUrl = (imageName: string | undefined) => {
  if (!imageName) {
    return "https://graduationdesign-1325357602.cos.ap-guangzhou.myqcloud.com/default.png";
  }
  return imageName.trim();
};

// 添加图片加载失败处理函数
const handleImageError = (e: Event) => {
  const img = e.target as HTMLImageElement;
  img.src =
    "https://graduationdesign-1325357602.cos.ap-guangzhou.myqcloud.com/default.png";
};

// 组件加载时获取购物车数据
onMounted(() => {
  loadCartItems();
});
</script>

<style scoped>
.cart-container {
  padding: 24px;
  background: #f5f5f5;
  min-height: 85vh;
}

.cart-card {
  background: #fff;
  border-radius: 4px;
}

.store-group {
  margin-bottom: 24px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
}

.store-header {
  padding: 16px 24px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.store-info {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 16px;
  font-weight: 500;
}

.cart-header {
  display: grid;
  grid-template-columns: 80px 400px 150px 150px 150px 100px;
  padding: 15px 24px;
  background: #f5f5f5;
  font-weight: bold;
}

.header-item {
  text-align: center;
}

.cart-items {
  padding: 0;
}

.cart-item {
  display: grid;
  grid-template-columns: 80px 400px 150px 150px 150px 100px;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.item-select {
  text-align: center;
}

.item-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.item-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.item-name {
  font-size: 14px;
  color: #333;
}

.item-size {
  font-size: 12px;
  color: #999;
}

.item-price,
.item-total {
  text-align: center;
  color: #e2231a;
  font-weight: bold;
}

.item-quantity {
  text-align: center;
}

.item-actions {
  text-align: center;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: #f5f5f5;
  border-top: 1px solid #f0f0f0;
  margin-top: 24px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-info {
  text-align: right;
}

.warning-text {
  color: #ff4d4f;
  margin-left: 8px;
}

.total-price {
  margin-left: 20px;
}

.price {
  color: #e2231a;
  font-size: 20px;
  font-weight: bold;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .cart-header,
  .cart-item {
    grid-template-columns: 60px 1fr 100px;
    gap: 10px;
    padding: 15px;
  }

  .header-item:nth-child(3),
  .header-item:nth-child(4),
  .header-item:nth-child(5),
  .item-price,
  .item-quantity,
  .item-total {
    display: none;
  }

  .store-header {
    padding: 12px 15px;
  }

  .cart-footer {
    flex-direction: column;
    gap: 15px;
    padding: 15px;
  }

  .footer-right {
    width: 100%;
    justify-content: space-between;
  }

  .total-info {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 4px;
  }
}
</style>
